// pages/my/settle/index.js
const app = getApp()
const {
  baseURL
} = require('../../../fetch/http')
const api = require('../../../fetch/api')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL: baseURL,
    show: false,
    address: {}
  },
  async address() {
    let res = await api.address()
    let arr = res.data
    if (arr.length > 0) {
      this.setData({
        address: arr[0]
      })
    }
  },
  async pay() {
    this.close()
    let {
      id
    } = this.data.address
    if (!id) {
      app.toast('请选择收货地址')
      return
    }
    let res = await api.buy({
      address_id: id,
      goods_spec_id: this.data.goods_spec_id,
    })
    // console.log(res);
    if (res.code == 200 && res.data) {
      api.wxpay(res.data).then(res => {
        if (res.errMsg == "requestPayment:ok") {
          app.toast('支付成功', 'success', () => {
            wx.redirectTo({
              url: '/pages/my/orders/index',
            })
          })
        }
      }).catch(error => {
        console.log(error);
      })
    } else {
      wx.redirectTo({
        url: '/pages/my/orders/index',
      })
    }
  },
  open() {
    this.setData({
      show: true
    })
  },
  close() {
    this.setData({
      show: false
    })
  },
  chooseAddress() {
    wx.navigateTo({
      url: '/pages/my/address/index?flag=true',
    })
  },
  async affirm() {
    let res = await api.affirm({
      goods_spec_id: this.data.goods_spec_id
    })
    let {
      goods,
      integral,
      payMoney,
      balance,
      payType
    } = res.data
    this.setData({
      goods,
      integral,
      payMoney,
      balance,
      payType
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goods_spec_id: options.id
    })
    this.affirm()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let {
      address
    } = app.globalData
    try {
      if (address) {
        this.setData({
          address
        })
      } else {
        this.address()
      }
    } catch (error) {
      console.log(error);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})